package com.yixun.qfbao.api.service.impl;

import com.beust.jcommander.internal.Lists;
import com.yixun.qfbao.api.service.DataPermissionService;
import com.yixun.qfbao.api.service.RoleCaseMemberService;
import com.yixun.qfbao.apidto.RoleCaseMemberDto;
import com.yixun.qfbao.apidto.SetRoleCaseMemberReqDto;
import com.yixun.qfbao.constant.RedisKeyConstant;
import com.yixun.qfbao.mapper.RoleCaseMemberMapper;
import com.yixun.qfbao.model.Node;
import com.yixun.qfbao.model.RoleCaseMember;
import com.yixun.qfbao.model.enums.DPDescEnum;
import com.yixun.qfbao.util.RedisUtil;
import com.yixun.qfbao.xf.model.enums.DeptPermissionEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class RoleCaseMemberServiceImpl implements RoleCaseMemberService {

    @Autowired
    private RoleCaseMemberMapper roleCaseMemberMapper;
    @Autowired
    private DataPermissionService dataPermissionService;

    @Override
    public Map<String, String> getDeptPermissionByRoleId(Long roleId) {
        Map<String, String> dpMap = new HashMap<>();
        // 选中的权限类型
        dpMap.put(DPDescEnum.DP_TYPE.getNo(), DeptPermissionEnum.ALL.getNo());
        List<RoleCaseMember> roleCaseMembers = roleCaseMemberMapper.listRoleCaseMember(roleId);
        if (CollectionUtils.isNotEmpty(roleCaseMembers)) {
            RoleCaseMember roleCaseMember = roleCaseMembers.get(0);
            dpMap.put(DPDescEnum.DP_TYPE.getNo(), StringUtils.defaultIfBlank(roleCaseMember.getDeptPermission(), DeptPermissionEnum.ALL.getNo()));
        }
        return dpMap;

    }

    @Override
    public RoleCaseMemberDto listRoleCaseMember(Long roleId, Long merchantId) {
        RoleCaseMemberDto dto = new RoleCaseMemberDto();
        Map<String, String> dpMap = getDeptPermissionByRoleId(roleId);
        List<Node> result = Lists.newArrayList();
        if (null != dpMap) {
            dto.setDeptPermission(dpMap.get(DPDescEnum.DP_TYPE.getNo()));
        }
        List<Node> nodes = roleCaseMemberMapper.listRoleDept(roleId, merchantId);
        if (nodes != null) {
            for (Node node : nodes) {
                //顶级部门
                if (node.getpId().equals("0")) {
                    node.setOther(node.getName());
                    if (StringUtils.isNotBlank(node.getrId())) {
                        node.setSelected(true);
                    } else {
                        node.setSelected(false);
                    }
                    result.add(node);
                }
                for (Node node1 : nodes) {
                    if (node1.getpId().equals(node.getId())) {
                        if (node.getChildren() == null) {
                            node.setChildren(Lists.newArrayList());
                        }
                        node1.setOther(node.getOther() + ";" + node1.getName());
                        if (StringUtils.isNotBlank(node1.getrId())) {
                            node1.setSelected(true);
                        } else {
                            node1.setSelected(false);
                        }
                        node.getChildren().add(node1);
                    }
                }
            }
        }
        dto.setRoleCaseMembers(result);
        return dto;
    }

    @Override
    public void saveRoleCaseMember(SetRoleCaseMemberReqDto reqDto) {
        roleCaseMemberMapper.deleteRoleCaseMemberByRoleId(Long.valueOf(reqDto.getUserId()), reqDto.getRoleId());
        // 清除此角色的楼盘权限
        dataPermissionService.cleanCompanyCacheByPartner(Long.valueOf(reqDto.getUserId()));
        String redisKey = RedisKeyConstant.Permission.DEV_ROLE_ORG_PERMISSION + reqDto.getRoleId();
        RedisUtil.delete(redisKey);
        if (Objects.nonNull(reqDto) && Objects.nonNull(reqDto.getRoleCaseMemberDto())) {
            RoleCaseMemberDto roleCaseMemberDto = reqDto.getRoleCaseMemberDto();
            List<RoleCaseMember> roleCaseMembers = Lists.newArrayList();
            if (StringUtils.equals(DeptPermissionEnum.NOT.getNo(), roleCaseMemberDto.getDeptPermission())) {
                List<String> selectedOrgs = roleCaseMemberDto.getSelected();
                if (CollectionUtils.isNotEmpty(selectedOrgs)) {
                    RoleCaseMember caseMember = new RoleCaseMember();
                    if (selectedOrgs.size() == 1 && "ALL".equals(selectedOrgs.get(0))) {
                        caseMember.setMerchantId(reqDto.getMerchantId());
                        caseMember.setDeptPermission(DeptPermissionEnum.NOT.getNo());
                        caseMember.setDeptId(0L);
                        caseMember.setRoleId(reqDto.getRoleId());
                        caseMember.setCreateUserId(Long.valueOf(reqDto.getUserId()));
                        caseMember.setCreateTime(Calendar.getInstance().getTime());
                        caseMember.setDelFlag("0");
                        roleCaseMembers.add(caseMember);
                    } else {
                        for (String deptId : selectedOrgs) {
                            caseMember = new RoleCaseMember();
                            caseMember.setMerchantId(reqDto.getMerchantId());
                            caseMember.setDeptPermission(DeptPermissionEnum.NOT.getNo());
                            caseMember.setDeptId(Long.parseLong(deptId));
                            caseMember.setRoleId(reqDto.getRoleId());
                            caseMember.setCreateUserId(Long.valueOf(reqDto.getUserId()));
                            caseMember.setCreateTime(Calendar.getInstance().getTime());
                            caseMember.setDelFlag("0");
                            roleCaseMembers.add(caseMember);
                        }
                    }
                }
            } else {
                RoleCaseMember roleCaseMember = new RoleCaseMember();
                roleCaseMember.setMerchantId(reqDto.getMerchantId());
                roleCaseMember.setDeptPermission(roleCaseMemberDto.getDeptPermission());
                roleCaseMember.setRoleId(reqDto.getRoleId());
                roleCaseMember.setCreateUserId(Long.valueOf(reqDto.getUserId()));
                roleCaseMember.setCreateTime(Calendar.getInstance().getTime());
                roleCaseMember.setDelFlag("0");
                roleCaseMembers.add(roleCaseMember);
            }
            if (roleCaseMembers.size() > 0) {
                roleCaseMemberMapper.saveAllRoleCaseMember(roleCaseMembers);
            }
        }
    }

    @Override
    public List<Long> listDeptByRoleId(Long roleId) {
        List<RoleCaseMember> roleCaseMembers = roleCaseMemberMapper.listRoleCaseMember(roleId);
        List<Long> deptIds = Lists.newArrayList();
        if (roleCaseMembers != null) {
            for (RoleCaseMember roleCaseMember : roleCaseMembers) {
                if (roleCaseMember.getDeptId() != null) {
                    deptIds.add(roleCaseMember.getDeptId());
                }
            }
        }
        return deptIds;
    }

    @Override
    public List<Long> listDeptByRoleIds(List<Long> roleIds) {
        List<Long> deptIds = Lists.newArrayList();
        List<RoleCaseMember> roleCaseMembers = roleCaseMemberMapper.listRoleCaseMemberByRoleIds(roleIds);
        if (CollectionUtils.isNotEmpty(roleCaseMembers)) {
            boolean flag = roleCaseMembers.stream().anyMatch(item ->
                    DeptPermissionEnum.ALL.getNo().equals(item.getDeptPermission())
                            || (DeptPermissionEnum.NOT.getNo().equals(item.getDeptPermission())
                            && item.getDeptId().compareTo(0L) == 0)
            );
            if (flag) {
                return deptIds;
            }
            for (RoleCaseMember roleCaseMember : roleCaseMembers) {
                if (DeptPermissionEnum.NOT.getNo().equals(roleCaseMember.getDeptPermission())) {
                    deptIds.add(roleCaseMember.getDeptId());
                }
            }
        }
        return deptIds;
    }

    @Override
    public List<Long> seleteDeptIdsByRoleIds(List<Long> roleIds) {
        List<RoleCaseMember> roleCaseMembers = roleCaseMemberMapper.seleteDeptIdsByRoleIds(roleIds);
        Set<Long> deptIds = roleCaseMembers.stream().map(RoleCaseMember::getDeptId).collect(Collectors.toSet());
        return new ArrayList<>(deptIds);
    }

}
